package com.netty.cn.model.http;

import com.netty.cn.model.http.handler.NettyServerFilter;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * 
 * @author wangzonghui
 * @date 2021-08-05 17:47:39
 * @Description http实例入口程序
 */
public class NettyServer {

	public void start(int port) throws Exception {

		ServerBootstrap serverBootstrap = new ServerBootstrap();
		// 做是否支持epoll轮询判断以获取更高性能
		EventLoopGroup group = Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup();
		
		String defaultUrl = "http://localhost:" + port + "/index";
		String testUrl = "http://localhost:" + port + "/test";

		System.out.println("连接地址：默认地址：" + defaultUrl + "\n 测试地址：" + testUrl);
		try {
			serverBootstrap.group(group);
			serverBootstrap.channel(Epoll.isAvailable() ? EpollServerSocketChannel.class : NioServerSocketChannel.class);
			serverBootstrap.childHandler(new NettyServerFilter()); // 设置过滤器
			// 服务器绑定端口监听
			ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
			System.out.println("http 服务端启动成功...");

			// 监听服务器关闭监听
			channelFuture.channel().closeFuture().sync();
		} finally {
			group.shutdownGracefully(); // 关闭EventLoopGroup，释放掉所有资源包括创建的线程
		}
	}

	public static void main(String[] args) throws Exception  {
		int port = 6789;
		new NettyServer().start(port);
	}
}
